/**
 * Created by Heiliuer on 2018/6/16 0016.
 */
const puppeteer = require('puppeteer')
const cheerio = require('cheerio')
const fs = require('fs')
const path = require('path')

// const URI = 'https://detail.m.tmall.com/item.htm?id=566741234264&scm=1007.14688.88974.0&pvid=9e75ecf2-d884-4a18-a44b-8f120e6ec6a9&spm=a211ue.11501597.recommend.6&sku_properties=10004:97505'
// const URI = 'https://item.m.jd.com/product/10271821230.html?jd_pop=f5c5f22d-d96b-4f17-ae5c-91b353fab2b3&abt=0'
// const URI = 'https://item.m.jd.com/product/4328004.html'
const URI = 'https://item.jd.com/3543802.html'

function getGood(url) {
    return puppeteer.launch({args: ['--no-sandbox', '--disable-setuid-sandbox']}).then(async browser => {
        const page = await browser.newPage();
        await page.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1')
        await page.goto(url)

        let bodyHTML = await page.evaluate(() => document.body.innerHTML)
        fs.writeFileSync(path.join(__dirname, '_crawler.html'), bodyHTML)
        const $ = cheerio.load(bodyHTML)
        const good = $good({$, url})
        await browser.close()
        return good
    })
}

function $good({$, url}) {
    const images = $('#loopImgUl > li > img').map((idx, dom) => {
        return getImage($(dom))
    }).get().filter(img => !isInValidImageUrl(img))

    const desc = ($('#commDesc').html() || '').toString()
    const descriptionImages = getDescriptionImages(desc)
    const title = $('#itemName').text()
    const price = ($('#priceSale > em').text() || $('#priceSaleChoice1').contents().last().text()).trim()
    return {
        coverImage: images[0],
        images,
        title,
        descriptionImages,
        price, // 68,
        crawlerUrl: url,
        json: ''
    }
}

//<br><img item_init_src="//img12.360buyimg.com/imgzone/jfs/t17179/231/1905099264/217336/6fdbf692/5aded23bNf19b6f3b.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img11.360buyimg.com/imgzone/jfs/t16885/100/1188787364/254698/b55f3bff/5ac0ab29Nf7f7ff6d.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img20.360buyimg.com/imgzone/jfs/t16681/32/1219064914/251291/a8efdb0f/5ac0ab29N4cd090ed.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img14.360buyimg.com/imgzone/jfs/t18679/39/1188707047/61525/727a87e4/5ac0ab29N748c681b.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img14.360buyimg.com/imgzone/jfs/t18742/67/1253260586/175823/ca49f7df/5ac0ab29N10eb6a9a.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img14.360buyimg.com/imgzone/jfs/t19414/192/1184048584/121328/4331aac4/5ac0ab27N063afd94.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img13.360buyimg.com/imgzone/jfs/t15547/138/2690826619/228120/efaddb98/5ac0ab2aNd1fc24af.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img12.360buyimg.com/imgzone/jfs/t16972/292/1269293670/53487/b9d058a5/5ac0ab2aNa7e9693b.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img13.360buyimg.com/imgzone/jfs/t17692/137/1247693729/179230/df219100/5ac0ab2aNc5eee109.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img30.360buyimg.com/imgzone/jfs/t19441/306/1226766073/198887/104afd1a/5ac0ab2aN18fe71c6.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img12.360buyimg.com/imgzone/jfs/t19258/252/1211151077/227450/a6d77a69/5ac0ab2aN5b36da56.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img20.360buyimg.com/imgzone/jfs/t18811/195/1188166546/146386/5efbd85f/5ac0ab2aNa490ab77.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img11.360buyimg.com/imgzone/jfs/t16690/33/1217628156/78974/93a6921/5ac0ab2aNad14d6b2.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img30.360buyimg.com/imgzone/jfs/t19396/310/1259908410/197813/921a73e8/5ac0ab2aNaf7ad387.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img13.360buyimg.com/imgzone/jfs/t16933/73/1794708633/215191/d0b35b0c/5ad71b7eNddb04966.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt=""><br><img item_init_src="//img12.360buyimg.com/imgzone/jfs/t16723/32/1733807396/229841/defdcc45/5ad71b0fN7ef45404.jpg.dpg" src="//wq.360buyimg.com/fd/h5/base/detail/images/transparent_a38f0a03.png" alt="">

function isInValidImageUrl(url) {
    if (url == null || url.trim == null) return true
    url = url.trim()
    if (url.indexOf('//') === 0 || url.indexOf('http://') === 0 || url.indexOf('https://') === 0) {
        return false
    }
    return true
}

function getImage($img) {
    let src = $img.attr('item_init_src')

    if (isInValidImageUrl(src)) {
        src = $img.attr('back_src')
    }

    if (isInValidImageUrl(src)) {
        src = $img.attr('src')
    }

    return src
}

function getDescriptionImages(detailString) {
    const $ = cheerio.load(detailString)
    const imgUrls = $('img').map((idx, dom) => {
        return getImage($(dom))
    }).get()
    if (!imgUrls.length) {
        let match
        let regex = /background-image:[\s]*url\((.*?)\)/g
        while (match = regex.exec(detailString)) {
            imgUrls.push(match[1])
        }
    }
    return imgUrls
}

// getGood(URI).then(good => {
//     console.log(good)
// })

module.exports.getGood = getGood

